package com.skyline.wo.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.imagine.provider.skyline.ImageResizeResult;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.skyline.base.exception.NoOperatePermissionException;
import com.skyline.base.exception.NoResourceException;
import com.skyline.base.exception.OperateFailedException;
import com.skyline.base.type.Activity;
import com.skyline.common.bean.Page;
import com.skyline.user.model.User;
import com.skyline.wo.dao.AlbumDao;
import com.skyline.wo.dao.PhotoDao;
import com.skyline.wo.model.Album;
import com.skyline.wo.model.Photo;
import com.skyline.wo.service.AlbumService;

@Service("albumService")
public class AlbumServiceImpl implements AlbumService {
	@Autowired
	private AlbumDao albumDao;
	@Autowired
	private PhotoDao photoDao;
	@Value("${album.cover.defaultCover}")
	private String cover;
	@Value("${album.cover.defaultExt}")
	private String ext;

	@Override
	public List<Album> listAlbumDetailsOfUserWithPortrait(long ownerId, long viewerId,
			int authority, Page page) {
		if (ownerId == 0) {
			ownerId = viewerId;
		}
		// 两者都为0，这种情况不应该存在
		if (ownerId == 0) {
			throw new NoResourceException("Id为0用户相册列表不存在");
		}
		return albumDao.queryAlbumDetailsByUserIdWithPortrait(ownerId, authority, page);
	}

	@Override
	public List<Album> listAlbumsOfUserWithoutPortrait(long ownerId, long viewerId, int authority,
			Page page) {
		if (ownerId == 0) {
			ownerId = viewerId;
		}
		// 两者都为0，这种情况不应该存在
		if (ownerId == 0) {
			throw new NoResourceException("Id为0用户相册列表不存在");
		}
		return albumDao.queryAlbumsByUserIdWithoutPortrait(ownerId, authority, page);
	}

	@Override
	public Album getAlbumById(long albumId) {
		Album album = albumDao.queryAlbumById(albumId);
		if (album == null) {
			throw new NoResourceException("Id为" + albumId + "的相册不存在");
		}
		Activity act = album.getActivity();
		if (act == Activity.DELETED || act == Activity.FREEZED) {
			throw new NoResourceException("Id为" + albumId + "的相册已删除或者已被屏蔽");
		}
		return album;
	}

	@Override
	public List<Photo> listPhotosOfAlbum(long albumId, long viewerId, int authority, Page page,
			boolean addVisit) {
		if (albumId == 0) {
			throw new NoResourceException("Id为0的相册不存在");
		}
		List<Photo> photos = photoDao.queryPhotosWithDetailOfAlbum(albumId, authority, page);
		// 非当前用户需要
		if (photos != null && !photos.isEmpty()) {
			long ownerId = photos.get(0).getOwnerId();
			if (addVisit && ownerId != viewerId) {
				albumDao.updateVisitCount(ownerId, albumId, 1);
			}
		}
		return photos;
	}

	@Override
	public void editAlbum(Album newAlbum) {
		Long albumId = newAlbum.getId();
		Long ownerId = newAlbum.getOwnerId();
		String newAlbumName = newAlbum.getAlbumName();
		String newPlace = newAlbum.getPlace();
		String newDescription = newAlbum.getDescription();
		Integer newAuthority = newAlbum.getAuthority();

		Album oldAlbum = getAlbumForChange(albumId, ownerId);
		boolean isModified = false;
		boolean shouldModifyPhotos = false;
		if (!StringUtils.equals(newAlbumName, oldAlbum.getAlbumName())) {
			isModified = true;
			shouldModifyPhotos = true;
		}
		if (!StringUtils.equals(newPlace, oldAlbum.getPlace())) {
			isModified = true;
		}
		if (!StringUtils.equals(newDescription, oldAlbum.getDescription())) {
			isModified = true;
		}
		if (!oldAlbum.getAuthority().equals(newAuthority)) {
			isModified = true;
			shouldModifyPhotos = true;
		}

		if (isModified) {
			albumDao.updateAlbumInfo(ownerId, albumId, newAlbumName, newPlace, newDescription,
					newAuthority);
		}
		if (shouldModifyPhotos) {
			photoDao.updatePhotoInfoOfAlbum(newAuthority, newAlbumName, albumId);
		}
	}

	@Override
	public Album getAlbumForChange(long albumId, long userId) {
		Album album = albumDao.queryAlbumDetailById(albumId);
		if(album == null) {
			throw new NoResourceException("Id为" + albumId + "的相册不存在！");
		}
		if (album.getOwnerId() != userId) {
			throw new NoOperatePermissionException("ID为" + userId + "的用户无法操作ID为" + albumId + "的相册");
		}
		Activity act = album.getActivity();
		if (act == Activity.DELETED || act == Activity.FREEZED) {
			throw new NoOperatePermissionException("Id为" + albumId + "的相册已删除或者已被屏蔽");
		}
		if (act == Activity.UNDELETABLE) {
			throw new NoOperatePermissionException("Id为" + albumId + "的相册为头像相册，不能修改");
		}
		return album;
	}

	@Override
	public Album createAlbum(User user, Album album) {
		long ownerId = user.getId();
		String ownerNickname = user.getNickname();
		String ownerPortrait = user.getPortrait();
		long albumId = albumDao.insertAlbumReturnId(ownerId, ownerNickname, ownerPortrait, album
				.getAlbumName(), album.getPlace(), album.getDescription(), album.getAuthority(),
				Activity.NORMAL, cover, ext);
		if (albumId != 0) {// 创建后只需要一些基本信息就可以，不需要设置所有信息
			album.setId(albumId);
			album.setOwnerId(ownerId);
			album.setOwnerNickname(ownerNickname);
			album.setOwnerPortrait(ownerPortrait);
			album.setPhotoNum(0);
			album.setActivity(Activity.NORMAL);
			album.setCover(cover);
			album.setCoverExt(ext);
			return album;
		} else {
			throw new OperateFailedException("ID为:" + ownerId + "的用户创建相册失败");
		}
	}

	@Override
	public void deleteAlbum(long albumId, long userId) {
		Album album = albumDao.queryAlbumById(albumId);
		if (album.getOwnerId() == userId) {
			Activity oldActivity = album.getActivity();
			if (oldActivity == Activity.NORMAL) {// 只能删除普通相册
				albumDao.updateAlbumActivity(album.getOwnerId(), albumId, Activity.DELETED);
				photoDao.updatePhotosActivityByAlbumId(albumId, Activity.DELETED);
			} else {
				throw new NoOperatePermissionException("ID为" + albumId + "的相册状态为" + oldActivity
						+ "，不能删除");
			}
		} else {
			throw new NoOperatePermissionException("ID为" + userId + "的用户没有删除ID为" + albumId
					+ "相册的权限");
		}
	}

	@Override
	public Photo getPhotoDetailById(long photoId, long viewerId, boolean addVisit) {
		if (photoId == 0) {
			throw new NoResourceException("Id为0的图片不存在");
		}
		Photo photo = photoDao.queryPhotoDetailById(photoId);
		if (photo == null) {
			throw new NoResourceException("Id为" + photoId + "的图片不存在");
		}
		Activity act = photo.getActivity();
		if (act == Activity.DELETED || act == Activity.FREEZED) {
			throw new NoResourceException("Id为" + photoId + "的照片已删除或者已被屏蔽");
		}
		if (addVisit && photo.getOwnerId() != viewerId) {
			photoDao.updateVisitCount(photo.getAlbumId(), photoId, 1);
		}
		return photo;
	}

	@Override
	public List<Photo> createPhotos(User owner, Album album, List<? extends ImageResizeResult> filesInfo) {
		long userId = owner.getId();
		String userNickname = owner.getNickname();
		String userPortrait = owner.getPortrait();
		long albumId = album.getId();
		String albumName = album.getAlbumName();
		int authority = album.getAuthority();
		Activity activity = album.getActivity();

		int size = filesInfo.size();
		List<String> fileKeys = new ArrayList<String>(size);
		List<String> middleFileKeys = new ArrayList<String>(size);
		List<String> smallFileKeys = new ArrayList<String>(size);
		List<String> fileExts = new ArrayList<String>(size);
		List<Long> fileSizes = new ArrayList<Long>(size);
		for (ImageResizeResult result : filesInfo) {
			String[] keys = result.getFileKeys();
			fileKeys.add(keys[0]);
			middleFileKeys.add(keys[1]);
			smallFileKeys.add(keys[2]);
			fileExts.add(result.getExt());
			fileSizes.add(result.getFileSize());
		}
		List<Long> ids = photoDao.insertPhotosReturnIds(userId, userNickname, userPortrait,
				albumId, albumName, authority, activity, fileKeys, middleFileKeys, smallFileKeys,
				fileExts, fileSizes);
		albumDao.updatePhotoCount(userId, albumId, ids.size());
		List<Photo> photos = new ArrayList<Photo>(size);
		for (int i = 0; i < size; i++) {
			ImageResizeResult result = filesInfo.get(i);
			String[] keys = result.getFileKeys();
			if(ids.get(i) == null) {//返回为空，表示插入失败
				continue;
			}
			Photo photo = new Photo();
			photo.setId(ids.get(i));
			photo.setOwnerId(userId);
			photo.setOwnerNickname(userNickname);
			photo.setOwnerPortrait(userPortrait);
			photo.setAlbumId(albumId);
			photo.setAlbumName(albumName);
			photo.setAuthority(authority);
			photo.setActivity(activity);
			photo.setFile(keys[0]);
			photo.setMiddleFile(keys[1]);
			photo.setSmallFile(keys[2]);
			photo.setExt(result.getExt());
			photo.setSize(result.getFileSize());
			photos.add(photo);
		}
		return photos;
	}

	@Override
	public void changePhotosDescription(long albumId, List<Long> ids, List<String> descriptions) {
		photoDao.updatePhotosDescription(albumId, descriptions, ids);
	}

	@Override
	public void changePhotoDescription(long albumId, long id, String descriptions) {
		photoDao.updatePhotoDescription(albumId, descriptions, id);
	}

	@Override
	public void changeAlbumCover(long ownerId, long albumId, String cover, String coverExt) {
		if (!StringUtils.isEmpty(cover)) {
			albumDao.updateAlbumCover(ownerId, albumId, cover, coverExt);
		}
	}

	@Override
	public void changePhotoAlbum(long ownerId, long photoId, long fromAlbumId, long toAlbumId) {
		photoDao.updatePhotoAlbum(photoId, toAlbumId);// 新相册照片数+1在修改同时完成
		albumDao.updatePhotoCount(ownerId, toAlbumId, 1);
		albumDao.updatePhotoCount(ownerId, fromAlbumId, -1);
	}

	@Override
	public Long deletePhoto(long userId, long photoId) {
		Photo photo = photoDao.queryPhotoById(photoId);
		if (photo.getOwnerId() == userId) {
			Activity oldActivity = photo.getActivity();
			if (oldActivity == Activity.NORMAL) {// 只能删除普通相册
				Long albumId = photo.getAlbumId();
				String file = photo.getSmallFile();
				Album album = albumDao.queryAlbumById(albumId);
				if (album.getOwnerId() != userId) {
					throw new NoOperatePermissionException("ID为" + userId + "的用户没有修改ID为" + albumId
							+ "相册的权限");
				}
				String cover = album.getCover();
				if (cover.equals(file)) {
					albumDao.updateRandomCoverAndPhotoCount(userId, albumId, photoId, this.cover,
							this.ext, -1);
				} else {
					albumDao.updatePhotoCount(userId, albumId, -1);
				}
				photoDao.updatePhotoActivity(album.getId(), photoId, Activity.DELETED);
				return album.getId();
			} else {
				throw new NoOperatePermissionException("Id为" + photoId + "的相册状态为" + oldActivity
						+ "，不能删除");
			}
		} else {
			throw new NoOperatePermissionException("Id为" + userId + "的用户没有删除Id为" + photoId
					+ "图片的权限");
		}
	}

	@Override
	public Photo getPhotoForChange(long userId, long photoId) {
		Photo photo = photoDao.queryPhotoDetailById(photoId);
		if(photo == null) {
			throw new NoResourceException("Id为" + photoId + "的图片不存在！");
		}
		if (photo.getOwnerId() != userId) {
			throw new NoOperatePermissionException("Id为" + userId + "的用户没有修改Id为" + photoId
					+ "图片的权限");
		}
		return photo;
	}

	@Override
	public List<Album> listAlbumNamesOfUser(long userId) {
		if (userId == 0) {
			throw new NoResourceException("Id为0用户相册列表不存在");
		}
		return albumDao.queryAlbumNamesOfUser(userId);
	}

	@Override
	public List<Photo> listPhotoFilesOfAlbum(long albumId, int authority) {
		if (albumId == 0) {
			throw new NoResourceException("Id为0的相册不存在");
		}
		return photoDao.queryPhotoFilesOfAlbum(albumId, authority);
	}

	@Override
	public Album getUserPortraitAlbum(long ownerId) {
		List<Album> albums = albumDao.queryUserAlbumByActivity(ownerId, Activity.UNDELETABLE);
		if (CollectionUtils.isEmpty(albums)) {
			throw new NoResourceException("Id为" + ownerId + "的用户不存在头像相册");
		} else {
			return albums.get(0);
		}
	}

	public void copyPhotoToPortraitAlbum(Album portraitAlbum, Photo photo) {
		long ownerId = portraitAlbum.getOwnerId();
		long portraitAlbumId = portraitAlbum.getId();
		String portraitAlbumName = portraitAlbum.getAlbumName();
		Activity portraitAlbumActivity = portraitAlbum.getActivity();

		photoDao.insertByCopyExistPhotoReturnId(portraitAlbumId, portraitAlbumName,
				portraitAlbumActivity, photo.getId());
		//头像相册照片数+1
		albumDao.updatePhotoCount(ownerId, portraitAlbumId, 1);
		String smallFile = photo.getSmallFile();
		String fileExt = photo.getExt();
		//修改头像相册封面
		changeAlbumCover(ownerId, portraitAlbumId, smallFile, fileExt); 
	}
	
	public Photo createPortraitPhoto(User owner, Album portraitAlbum, ImageResizeResult result) {
		long ownerId = owner.getId();
		List<Photo> photos = createPhotos(owner, portraitAlbum, Arrays.asList(result));
		if(photos.isEmpty()) {
			throw new OperateFailedException("插入头像相册失败");
		}
		Photo portrait = photos.get(0);
		String smallFile = portrait.getSmallFile();
		String fileExt = portrait.getExt();
		//修改头像相册封面
		changeAlbumCover(ownerId, portraitAlbum.getId(), smallFile, fileExt);
		return portrait;
	}
	
	public Photo getUserCurrentPortraitPhoto(long userId) {
		Album portraitAlbum = getUserPortraitAlbum(userId);
		return getCurrentPortraitPhotoFromAlbum(portraitAlbum);
	}
	
	public Photo getCurrentPortraitPhotoFromAlbum(Album portraitAlbum) {
		long portraitAlbumId = portraitAlbum.getId();
		Activity portraitAlbumActivity = portraitAlbum.getActivity();
		
		return photoDao.queryLatestPhotoOfAlbum(portraitAlbumId, portraitAlbumActivity);
	}

	/** -------------------华丽的分割线，下面的还没实现呢-------------------------------- **/

	// @Override
	// public Photo getPhotoForChangePhoto(long photoId, long userId) {
	// // TODO Auto-generated method stub
	// return null;
	// }

	// @Override
	// public List<Album> listAlbumsOfUserWithoutPortrait(long ownerId, long
	// viewerId, int authority, Page page) {
	// if (ownerId == 0) {
	// ownerId = viewerId;
	// }
	// // 两者都为0，这种情况不应该存在
	// if (ownerId == 0) {
	// throw new NoResourceException("Id为" + ownerId + "用户相册列表不存在");
	// }
	// return albumDao.queryActiveAlbumsByUserId(ownerId, authority, page);
	// }

	// @Override
	// public Album getAlbumDetailById(long albumId) {
	// Album album = albumDao.queryAlbumDetailById(albumId);
	// if (album == null) {
	// throw new NoResourceException("Id为" + albumId + "的相册不存在");
	// }
	// Activity act = album.getActivity();
	// if (act == Activity.DELETED || act == Activity.FREEZED) {
	// throw new NoResourceException("Id为" + albumId + "的相册已删除或者已被屏蔽");
	// }
	// return album;
	// }

	// @Override
	// public List<Photo> listPhotosOfAlbumForChange(long albumId, long
	// viewerId) {
	// List<Photo> photos = photoDao.queryPhotosOfAlbum(albumId);
	// if (!photos.isEmpty()) {
	// if (photos.get(0).getOwnerId() != viewerId) {
	// throw new NoOperatePermissionException();
	// }
	// }
	// return photos;
	// }
}
